<template>
  <div>
    <!-- 添加用户 -->
    <div>
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" status-icon
        hide-required-asterisk="false">
        <el-form-item label="用户类型" prop="type">
          <el-radio-group v-model="ruleForm.type" @change="changeType(ruleFormRef, ruleForm.type)">
            <el-radio :label="1">普通用户</el-radio>
            <el-radio :label="0">管理员</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username" placeholder="请输入昵称"/>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realname">
          <el-input v-model="ruleForm.realname" placeholder="请输入真实姓名"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password" type="password" show-password placeholder="请输入密码"/>
        </el-form-item>
        <el-form-item label="身高" prop="height" v-if="ruleForm.type == 1">
          <el-input v-model="ruleForm.height" type="number" @keydown="handleKeyDown"  placeholder="请输入身高，单位为厘米">
          </el-input>
        </el-form-item>
        <el-form-item label="体重" prop="weight" v-if="ruleForm.type == 1">
          <el-input v-model="ruleForm.weight" type="number" @keydown="handleKeyDown" placeholder="请输入体重，单位为公斤">
          </el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="ruleForm.phone" placeholder="请输入电话号码"/>
        </el-form-item>
        <el-form-item label="BMI值" prop="bmi" v-if="ruleForm.type == 1">
          <el-input v-model="bmi" disabled />
        </el-form-item>
        <el-form-item label="出生日期" prop="birthDay" v-if="ruleForm.type == 1">
          <div class="demo-date-picker">
            <div class="block">
              <el-date-picker v-model="ruleForm.birthDay" type="date" placeholder="请选择日期"
                :disabled-date="disabledDate" :shortcuts="shortcuts" />
            </div>
          </div>
        </el-form-item>
        <el-form-item label="性别" prop="gender" v-if="ruleForm.type == 1">
          <el-radio-group v-model="ruleForm.gender">
            <el-radio label="female">女</el-radio>
            <el-radio value="male" label="male">男</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="糖尿病类型" prop="specialCondition" v-if="ruleForm.type == 1">
          <el-radio-group v-model="ruleForm.specialCondition">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">Ⅰ型糖尿病</el-radio>
            <el-radio :label="2">Ⅱ型糖尿病</el-radio>
            <el-radio :label="3">混合型糖尿病</el-radio>
            <el-radio :label="4">其他特殊类型</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="用户状态" prop="status" v-if="ruleForm.type == 1">
          <el-radio-group v-model="ruleForm.status">
            <el-radio :label="0">停用</el-radio>
            <el-radio :label="1">正常</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>
    <span class="dialog-footer">
      <el-button type="primary" @click="submitFormAdd(ruleFormRef)">提交</el-button>
      <el-button @click="resetForm(ruleFormRef)">重置表单</el-button>
      <el-button @click="handleReturn">取消</el-button>
    </span>
  </div>
</template>

<script>
import { ref, reactive, computed } from 'vue'
import request from '../../utils/request'
import { ElNotification } from 'element-plus'
import { useRouter } from 'vue-router'
export default {
  components: {},
  setup() {
    const router = useRouter()
    //判断用户名是否存在
    const isExist = ref(false)
    const adminIsExist = ref(false)
    const checkHeight = (rule, value, callback) => {
      if (value > 250) {
        callback(new Error(rule.message))
      } else {
        callback()
      }
    }
    const checkWeight = (rule, value, callback) => {
      if (value > 300) {
        callback(new Error(rule.message))
      } else {
        callback()
      }
    }

    const checkPhone = (rule, value, callback) => {
      if (/^((0\d{2,3}-?\d{7,8})|(1[3465789]\d{9}))$/.test(value) == false) {
        callback(new Error(rule.message))
      } else {
        callback()
      }
    }

    const checkUserName = async (rule, value, callback) => {
      isExist.value = await handleExist()
      adminIsExist.value = await handleAdminIsExist()
      console.log(isExist.value,999999);
      if (isExist.value == true || adminIsExist.value == true) {
        callback(new Error(rule.message))
      } else {
        callback()
      }
    }

    const lxfs = /^((0\d{2,3}-?\d{7,8})|(1[3465789]\d{9}))$/ //验证电话

    const rules = reactive({
      username: [
        {
          required: true,
          message: '请输入用户名',
          trigger: 'blur',
        },
        {
          validator: checkUserName,
          message: '用户名重复，请重新输入',
        }
      ],
      realname: [
        {
          required: false,
          message: '请输入真实姓名',
          trigger: 'blur',
        },
      ],
      password: [
        {
          required: true,
          message: '请输入密码',
          trigger: 'blur',
        },
      ],
      gender: [
        {
          required: true,
          message: '请选择性别',
          trigger: 'change',
        },
      ],
      height: [
        {
          required: true,
          message: '请输入身高',
          trigger: 'blur',
        },
        {
          validator: checkHeight,
          message: '请输入正确的身高(0~250)',
        },
      ],
      weight: [
        {
          required: true,
          message: '请输入体重',
          trigger: 'blur',
        },
        {
          validator: checkWeight,
          message: '请输入正确的体重(0~300)',
        },
      ],
      phone: [
        {
          required: false,
          message: '请输入电话号码',
          trigger: 'blur',
        },
        {
          validator: checkPhone,
          message: '请输入正确的电话号码',
        },
      ],
      birthDay: [
        {
          required: true,
          message: '请选择出生日期值',
          trigger: 'change',
        },
      ],
      specialCondition: [
        {
          required: true,
          message: '请选择特殊类型',
          trigger: 'change',
        },
      ],
    })
    const handleKeyDown = (event) => {
      if (event.key === 'e') {
        event.preventDefault()
      }
    }

    const ruleFormRef = ref({})
    const ruleForm = reactive({
      birthDay: '',
      createdAt: '',
      password: '',
      gender: 'female',
      logoImg: '',
      phone: '',
      specialCondition: 0,
      status: 1,
      type: 1,
      userId: '',
      username: '',
      height: '',
      weight: '',
      bmi: '',
      realname: '匿名',
    })

    // 重置表单
    const resetForm = (formEl) => {
      if (!formEl) return
      formEl.resetFields()
    }
    // 切换用户类型清除数据
    const changeType = (formEl, type) => {
      if (!formEl) return
      if (type == 0) {
        formEl.resetFields()
        ruleForm.height = ''
        ruleForm.weight = ''
        ruleForm.bmi = ''
        ruleForm.type = 0
        ruleForm.birthDay = ''
        ruleForm.gender = 'other'
        ruleForm.status = 1
        ruleForm.specialCondition = 0
      } else {
        formEl.resetFields()
      }
    }
    // 处理时间函数
    function dateTOString(date) {
      var source = new Date(date)
      var yy = source.getFullYear().toString()
      var mm = source.getMonth() + 1
      mm = mm < 10 ? '0' + mm.toString() : mm.toString()
      var dd = source.getDate()
      dd = dd < 10 ? '0' + dd.toString() : dd.toString()
      var aa = yy + '-' + mm + '-' + dd
      return aa
    }
    const formData = ref(null)

    // 计算bmi
    const bmi = computed(() => {
      if (ruleForm.height === '' || ruleForm.weight === '') {
        return
      }
      return (
        ruleForm.weight /
        (((ruleForm.height / 100) * ruleForm.height) / 100)
      ).toFixed(1)
    })

    //判断用户名是否存在
    /* const isExist = ref(false)
    const adminIsExist = ref(false) */
    const handleExist = async () => {
      return await request
        .request({
          url: '/user/getUserIsExist',
          method: 'get',
          params: {
            username: ruleForm.username,
          },
        })
        .then((res) => {
          return res.data.data.isExist
          // }
        })
    }
    const handleAdminIsExist = async () => {
      return await request
        .request({
          url: '/user/getAdminIsExist',
          method: 'get',
          params: {
            username: ruleForm.username,
          },
        })
        .then((res) => {
          return res.data.data.isExist
          // }
        })
    }
    const submitFormAdd = async (formEl) => {
      if (!formEl) return
      if (ruleForm.birthDay) {
        ruleForm.birthDay = dateTOString(ruleForm.birthDay)
      } else {
        ruleForm.birthDay = ''
      }
      // isExist.value = await handleExist()
      // adminIsExist.value = await handleAdminIsExist()
      /*       if (isExist.value == true) {
              ElNotification({
                title: '添加失败,用户名已存在',
                message: '请联系管理员检查失败原因',
              })
              return
            }
            if (adminIsExist.value == true) {
              ElNotification({
                title: '添加失败,用户名已存在',
                message: '请联系管理员检查失败原因',
              })
              return
            } */
      await formEl.validate((valid, fields) => {
        if (valid) {
          ruleForm.bmi = bmi
          request
            .request({
              url: '/user/add',
              method: 'post',
              data: {
                // userId: ruleForm.userId,
                username: ruleForm.username,
                realname: ruleForm.realname,
                password: ruleForm.password,
                logoImg: ruleForm.logoImg,
                gender: ruleForm.gender,
                height: Number(ruleForm.height),
                weight: Number(ruleForm.weight),
                phone: ruleForm.phone,
                bmi: ruleForm.bmi,
                status: ruleForm.status,
                type: ruleForm.type,
                specialCondition: ruleForm.specialCondition,
                birthDay: ruleForm.birthDay,
              },
            })
            .then((res) => {
              if (res.data.code == 200) {
                ElNotification({
                  title: '添加成功',
                  message: '成功添加用户信息',
                })
                router.push('userTable')
              } else {
                ElNotification({
                  title: '添加失败,用户名已存在',
                  message: '用户名已存在',
                })
              }
            })
            .catch((e) => {
              ElNotification({
                title: '添加失败,请求超时',
                message: '请联系管理员检查失败原因' + e,
              })
            })
        } else {
          ElNotification({
            title: '校验失败',
            message: '请重新填写信息',
          })
        }
      })
    }

    const handleReturn = () => {
      router.push('/userTable')
    }

    return {
      ruleForm,
      ruleFormRef,
      rules,
      // submitForm,
      resetForm,
      changeType,
      submitFormAdd,
      handleKeyDown,
      handleReturn,
      bmi,
    }
  },
}
</script>

<style lang="scss" scoped></style>

<style>
.el-upload--text {
  height: auto;
  width: auto;
}

.mavonEditor {
  width: 100%;
  height: 100%;
}
</style>
